package com.sakura.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import com.sakura.po.TextMessage;
import com.thoughtworks.xstream.XStream;

public class MessageUtil {
	
	public static Map<String, String> xmlToMap(HttpServletRequest request) throws IOException, DocumentException{
		Map<String, String> map = new HashMap<String, String>();
		SAXReader reader = new SAXReader();
		InputStream ins = request.getInputStream();
		Document doc = reader.read(ins);
		
		Element root = doc.getRootElement();
		@SuppressWarnings("unchecked")
		List<Element> elements = root.elements();
		for (Element element : elements) {
			map.put(element.getName(), element.getText());
		}
		ins.close();
		return map;
	}
	
	public static String textMessageToXml(TextMessage TextMessage){
		XStream xStream = new XStream();
		xStream.alias("xml", TextMessage.getClass());
		return xStream.toXML(TextMessage);
	}

}
